package io.gitee.zhangbinhub.acp.boot

import com.fasterxml.jackson.databind.ObjectMapper
import io.gitee.zhangbinhub.acp.boot.constant.AcpCoreConstant
import io.gitee.zhangbinhub.acp.boot.exceptions.AcpWebExceptionHandler
import io.gitee.zhangbinhub.acp.boot.exceptions.ReactiveExceptionHandler
import io.gitee.zhangbinhub.acp.boot.exceptions.ServletExceptionHandler
import io.gitee.zhangbinhub.acp.boot.interfaces.LogAdapter
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication
import org.springframework.context.annotation.Bean
import org.springframework.core.annotation.Order
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler

/**
 * @author zhang by 31/07/2019
 * @since JDK 11
 */
@AutoConfiguration(after = [AcpComponentAutoConfiguration::class])
class AcpExceptionAutoConfiguration {

    @Bean
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    @ConditionalOnMissingBean(ResponseEntityExceptionHandler::class)
    fun servletExceptionHandler(
        logAdapter: LogAdapter,
        acpWebExceptionHandlerList: List<AcpWebExceptionHandler>,
        objectMapper: ObjectMapper
    ) = ServletExceptionHandler(logAdapter, acpWebExceptionHandlerList, objectMapper)

    @Bean
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
    @Order(AcpCoreConstant.reactiveErrorWebExceptionHandlerOrder)
    fun reactiveExceptionHandler(
        logAdapter: LogAdapter,
        acpWebExceptionHandlerList: List<AcpWebExceptionHandler>,
        objectMapper: ObjectMapper
    ) = ReactiveExceptionHandler(logAdapter, acpWebExceptionHandlerList, objectMapper)

}